/*
 * EchoParse.cpp
 *
 *  Created on: 2012-12-24
 *      Author: yangentao@gmail.com
 */
#include <assert.h>
#include "EchoParse.h"
#include "../yet/StreamLog.h"

namespace ftp {
using namespace yet;

EchoSeg::EchoSeg(){
	code = 0;
}
void EchoSeg::clear() {
	code = 0;
	lines.clear();
}

int isMultiBegin(string& s) {
	if (s.size() >= 4) {
		if (isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2]) && (s[3] == '-')) {
			return  atoi(s.c_str());
		}
	}
	return 0;
}
bool isMultiEnd(string& s, int multiBeginCode) {
	if (s.size() >= 4) {
		if (isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2]) && (s[3] == ' ')) {
			return multiBeginCode == atoi(s.c_str());
		}
	}
	return false;
}
int isSingleEnd(string& s) {
	if (s.size() >= 4) {
		if (isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2]) && (s[3] == ' ')) {
			return  atoi(s.c_str());
		}
	}
	return 0;
}
int getCode(string& s) {
	if (s.size() >= 4) {
		string code = s.substr(0, 3);
		return atoi(code.c_str());
	}
	return 0;
}

EchoParse::EchoParse() {

}

EchoParse::~EchoParse() {
}

void EchoParse::clear(){
	echos.clear();
}
bool EchoParse::empty(){
	return echos.empty();
}
int  EchoParse::size(){
	return echos.size();
}
int EchoParse::getCode(int index){
	assert(index < size());
	return echos[index].code;
}
vector<string> EchoParse::getLines(int index){
	assert(index < size());
	return echos[index].lines;
}
void EchoParse::parse(String echo) {
	parse(string(echo.buffer(), echo.size()));
}
void EchoParse::parse(string echo) {
	echos.clear();
	if (echo.size() < 4) {
		return;
	}
	LineParse p(echo);
	int count = p.getLineCount();
	EchoSeg currentSeg;
	for (int i = 0; i < count; ++i) {
		if (!p.endWithCrLf(i)) {
			return;
		}
		string sline = p.getLineText(i);
		if (currentSeg.code == 0) {
			int code = isSingleEnd(sline);
			if (code) {
				EchoSeg seg;
				seg.code = code;
				seg.lines.push_back(sline);
				echos.push_back(seg);
				continue;
			}
			code = isMultiBegin(sline);
			if (code) {
				currentSeg.clear();
				currentSeg.code = code;
				currentSeg.lines.push_back(sline);
				continue;
			}
			slog << err << "Unknown resopnse: " << echo << endln;
		} else {
			if (isMultiEnd(sline, currentSeg.code)) {
				currentSeg.lines.push_back(sline);
				echos.push_back(currentSeg);
				currentSeg.clear();
			} else {
				currentSeg.lines.push_back(sline);
			}

		}
	}
}

} /* namespace yet */
